<template>
  <div class="body1">
    <div class="no-print el-button-print">
      <el-button @click="addForm">添加页</el-button>
      <el-button @click="deleteForm">删除页</el-button>
      <el-button @click="exportPDF">导出为pdf</el-button>
    </div>
    <div class="body2" id="pdfDom" :class="{ 'pdf-export': isPdfExport }">
      <div v-for="(item, index) in form" :key="index" :class="{ 'page-break': index !== 0 }">
        <div class="title">
          <div class="biaotididian">{{ agencyName }}</div>
          <div class="biaoti">现场照片及说明</div>
        </div>
        <table class="tableStyle">
          <colgroup>
            <col width="55%">
            <col width="45%">
          </colgroup>
          <tr style="height: 450px;">
            <td colspan="2">
              <div style="display: flex; align-items: center; justify-content: center;  height: 450px;"
                class="image-container" @click="chooseImage(index)">
                <img v-if="!isLoading && item.imageSrc" :src="item.imageSrc" alt="现场照片"
                  style="max-height: 99%; max-width: 99%;">
                <input type="file" accept="image/*" style="display: none" ref="imageInput" @change="handleFileChange">
                <div v-if="!item.imageSrc || isLoading" class="placeholder-image" @click="chooseImage(index)"></div>
              </div>
            </td>
          </tr>
          <tr>
            <td colspan="2" style="height: 25px;">照片内容: <input v-model="item.text1" class="areaInputStyle" type="text"
                style="width: 520px;" maxlength="27">
            </td>
          </tr>
          <tr>
            <td style="height: 50px; display: flex; border: 0px; align-items: center; ">拍摄地点：
              <div style=" width: 240px; height: 50px; display: inline-block; vertical-align: top;">
                <el-input v-model="item.text2" :resize="'none'" autosize class="areaInputStyle" type="textarea"
                  maxlength="24"></el-input>
              </div>
            </td>
            <td>拍摄人: <input v-model="item.text3" class="areaInputStyle" type="text" style="width: 160px;" maxlength="8">
            </td>
          </tr>
          <tr>
            <td style="height: 25px;">
              拍摄时间:
              <span>
                <editable-textarea :text="form[index].data1" param-type="YYYY-MM-DD HH:mm"
                  @send-to-parent="(data, type) => receiveFromChild(data, type, index)"></editable-textarea>
              </span>
            </td>
            <td>制作人: <input v-model="item.text4" class="areaInputStyle" type="text" style="width: 160px" maxlength="8">
            </td>
          </tr>
          <tr>
            <td colspan="2" style="height: 25px;">
              <div style="line-height: 25px;">
                <span style="width: 75px; display: inline-block; height: 25px;">当事人:</span>
                <div style="width: 530px;height: 25px; display:inline-block;">
                  <privy-info-select-return-array v-model="item.unitName" :isTable="true" maxLength="28"
                    return-fields="A" :return-array-template="[
                      { name: 'companyAddress', field: 'E' },
                      { name: 'legalPersonPhone', field: 'H' },
                    ]" @select="(data) => selectUnitUpdateData(data, index)">
                  </privy-info-select-return-array>
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td colspan="2" style="height: 25px;">见证人: <input v-model="item.text6" class="areaInputStyle" type="text"
                style="width: 530px;" maxlength="28">
            </td>
          </tr>
          <tr>
            <td rowspan="2" style="height: 50px;">
              <div style="flex:1;display: flex;justify-content: left;">
                <span style="padding-top: 4px;"> 行政执法人员:</span>
                <InvestigatorSelect v-model="item.a4" :id-field="'a5'"
                  @change="(payload) => handleInvestigatorChange(payload, index)" />
              </div>

              <div style="flex:1;display: flex;justify-content: left;">
                <span style="padding-top: 4px;">行政执法人员:</span>
                <InvestigatorSelect v-model="item.a8" :id-field="'a9'"
                  @change="(payload) => handleInvestigatorChange(payload, index)" />
              </div>
            </td>
            <td rowspan="2">
              <div style="display: inline-flex; align-items: center;">
                执法证件号:{{ item.a5 }}
              </div><br>
              <div style="display: inline-flex; align-items: center;">
                执法证件号:{{ item.a9 }}
              </div>
            </td>
          </tr>
          <tr></tr>
          <tr>
            <td style="height: 75px; display: flex; border: 0px; align-items: center; ">当事人联系地址：
              <div style=" width: 180px; height: 75px; display: inline-block; vertical-align: top;">
                <el-input v-model="item.companyAddress" :resize="'none'" autosize class="areaInputStyle" type="textarea"
                  maxlength="27"></el-input>
              </div>
            </td>
            <td>联系电话: <input class="areaInputStyle" type="text" style="width: 170px;" v-model="item.legalPersonPhone"
                oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')" maxlength="18"></td>
          </tr>
          <tr height="100px;">
            <td colspan="2" style="text-align: left;vertical-align: top; position: relative;">
              <span>备注：</span>
              <el-input type="textarea" v-model="item.text13" :rows="text13Config[index]?.maxLines"
                @keydown.native="handleKeyDown('text13-' + index, $event)"
                @input="handleInput('text13-' + index, $event)" @paste.native="handlePaste('text13-' + index, $event)"
                class="el-textarea-hidden" style="white-space: pre;overflow-x: auto;font-family: monospace;"
                wrap="soft" />
            </td>
          </tr>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { createInputLimiter } from '@/utils/limitInput';
import EditableTextarea from "@/views/template/EditableTextarea";
import { agencyName, sealName } from "../../utils/publicName.js"
import PrivyInfoSelectReturnArray from "@/views/template/PrivyInfoSelectReturnArray";
import InvestigatorSelect from "@/views/template/InvestigatorSelect";

export default {

  components: {
    EditableTextarea,
    InvestigatorSelect,
    PrivyInfoSelectReturnArray,
  },
  data() {
    return {
      resultImgurl: '',
      isLoading: false,
      isPdfExport: false, // 控制打印样式
      currentItem: {},
      agencyName: agencyName,
      sealName: sealName,
      form: [
        {
          imageSrc: '',
          text1: '',
          text2: '',
          text3: '',
          data1: '',
          text4: '',
          // Initialize other fields as needed
        },
      ],
      identificationNumber: '',
      text13Config: [],
    };
  },

  created() {
    window.parent.getTemplateData((data) => {
      this.form = data;
      console.log("2", this.form)
      for (let i = 0; i < this.form.length; i++) {
        this.text13Config.push({
          maxLines: 3,
          charsPerLine: 32 * 2,
          maxLength: 3 * 32 * 2,
          inputLimiter: null,
          displayText: ''
        })
        this.text13Config[i].inputLimiter = createInputLimiter(this, {
          maxLines: this.text13Config[i].maxLines,
          charsPerLine: this.text13Config[i].charsPerLine,
          maxLength: this.text13Config[i].maxLength,
          propName: `form[${i}].text13`
        });
      }
    })
    window.postForm = () => {
      this.postForm();
    }
  },

  mounted() {
    window.parent.changeTemplateDow();
    // this.getInvestigators();
  },

  methods: {
    // 添加
    addForm() {
      this.form.push({
        imageSrc: '',
        text1: '',
        text2: '',
        text3: '',
        data1: '',
        text4: '',
        // Initialize other fields as needed
      });
      this.text13Config.push({
        maxLines: 3,
        charsPerLine: 32 * 2,
        maxLength: 3 * 32 * 2,
        inputLimiter: null,
        displayText: ''
      })
      this.text13Config[this.text13Config.length - 1].inputLimiter = createInputLimiter(this, {
        maxLines: this.text13Config[this.text13Config.length - 1].maxLines,
        charsPerLine: this.text13Config[this.text13Config.length - 1].charsPerLine,
        maxLength: this.text13Config[this.text13Config.length - 1].maxLength,
        propName: `form[${this.text13Config.length - 1}].text13`
      });
    },
    getConfigName(field) {
      // 将field按-拆分
      const parts = field.split('-');
      const index = parts[1];
      switch (field) {
        case 'text13-' + index:
          return this.text13Config[index];
      }
    },
    handleKeyDown(field, e) {
      const config = this.getConfigName(field);
      config.inputLimiter.handleKeyDown(e);
    },
    handleInput(field, value) {
      const config = this.getConfigName(field);
      const parts = field.split('-');
      const field1 = parts[0]
      const index = parts[1];
      // form数组的第index个中的filed1属性
      this.form[index][field1] = config.inputLimiter.handleInput(value);
    },
    handlePaste(field, e) {
      const config = this.getConfigName(field);
      config.inputLimiter.handlePaste(e);
    },
    // 删除页
    deleteForm() {
      if (this.form.length > 1) {
        this.form.pop();
        this.text13Config.pop();
      } else {
        // 使用Element UI的提示（确保已引入ElMessage）
        this.$message.warning('至少需要保留一页');
      }
    },

    chooseImage(index) {
      this.currentItem = this.form.at(index)
      this.$refs["imageInput"][index].click();
    },
    // 导出为pdf
    exportPDF() {
      this.savePDF()
        .then((blob) => {
          const blobUrl = URL.createObjectURL(blob);

          // 先预览
          const previewWindow = window.open(blobUrl, '_blank');

          // 自动下载
          const fileName = `现场照片及说明.pdf`;
          const downloadLink = document.createElement('a');
          downloadLink.href = blobUrl;
          downloadLink.download = fileName;
          document.body.appendChild(downloadLink);
          downloadLink.click();
          document.body.removeChild(downloadLink);

          // 监听预览窗口关闭后释放内存
          if (previewWindow) {
            const timer = setInterval(() => {
              if (previewWindow.closed) {
                clearInterval(timer);
                URL.revokeObjectURL(blobUrl);
              }
            }, 1000);
          } else {
            setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); // 兜底释放
          }
        })
        .catch(error => {
          console.error('导出PDF出错:', error);
          alert('导出失败，请重试或联系管理员');
        });
    },
    savePDF() {
      this.isPdfExport = true; // 激活PDF样式
      return new Promise((resolve, reject) => {
        this.$nextTick(() => {
          import('html2pdf.js').then((module) => {
            const html2pdf = module.default;

            //获取所有需要替换的 el-input
            const elInputs = document.querySelectorAll('.el-input__inner, .el-textarea__inner');

            //存储原始元素和它们的父节点，方便后续恢复
            const originalElements = [];

            elInputs.forEach((input) => {
              const div = document.createElement('div');
              div.style.whiteSpace = 'pre-wrap'; // 保留换行
              div.style.fontFamily = '仿宋';
              div.style.fontSize = '5mm';
              div.textContent = input.value; // 保留原内容（自动处理 \n 换行）
              div.style.lineHeight = '1.3';

              // 替换 el-input，并存储原始元素
              originalElements.push({
                parent: input.parentNode,
                original: input,
                replacement: div,
              });
              input.parentNode.replaceChild(div, input);
            });

            // 配置选项
            const opt = {
              margin: 0,
              image: {
                type: 'jpeg',
                quality: 0.98
              },
              html2canvas: {
                scale: 2,
                logging: false,
                useCORS: true
              },
              jsPDF: {
                unit: 'mm',
                format: 'a4',
                orientation: 'portrait'
              }
            };

            const element = document.getElementById('pdfDom');

            // 生成PDF Blob对象
            html2pdf()
              .set(opt)
              .from(element)
              .toPdf()
              .get('pdf')
              .then((pdf) => {
                const blob = pdf.output('blob');

                resolve(blob); // 返回Blob对象
              })
              .catch((error) => {
                reject(error);
              })
              .finally(() => {
                this.isPdfExport = false; // 恢复原始样式
                // 恢复原始input
                originalElements.forEach(({ parent, original, replacement }) => {
                  parent.replaceChild(original, replacement);
                });
              });
          }).catch((error) => {
            reject(error);
            this.isPdfExport = false;
            originalElements.forEach(({ parent, original, replacement }) => {
              parent.replaceChild(original, replacement);
            });
          });
        });
      });
    },
    //父页面提交按钮将调用此方法，此方法将文书数据回传到父页面的请求方法中
    postForm() {
      this.savePDF()
        .then((blob) => {


          // 创建FormData并添加文件
          const formData = new FormData();
          formData.append('file', blob, '现场照片及说明.pdf');

          window.parent.postTemplateDate(this.form, formData);
        })
        .catch(error => {
          console.error('整个保存PDF出错:', error);
        });
    },

    //选择日期时间
    receiveFromChild(data, type, index) {
      const TypeMap = {
        'YYYY-MM-DD HH:mm': 'data1',
      };
      if (TypeMap[type] && this.form[index]) {
        this.form[index][TypeMap[type]] = data;
      }
    },

    //选择执法人员
    handleInvestigatorChange(payload, index) {
      const { identificationNumber, idField } = payload;  // 从payload中解构证件号和目标字段
      // 确保索引和字段有效，再填充证件号
      if (idField && identificationNumber && this.form[index]) {
        this.form[index][idField] = identificationNumber;  // 更新当前item的指定字段
      }
    },


    // 选择图片
    async handleFileChange(event) {
      try {
        const file = event.target.files[0];
        const reader = new FileReader();
        reader.onload = () => {
          this.currentItem.imageSrc = reader.result;
        };
        if (file) {
          this.isLoading = true;
          reader.readAsDataURL(file);
          setTimeout(() => {
            this.isLoading = false;
          }, 2000);

          const formData = new FormData();
          // 添加 file 属性，并指定文件名
          formData.append('file', file);

          // 设置 Content-Type 头部为 multipart/form-data
          const config = {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          };

          const response = await axios.post('/api/related-file/uploadSign', formData, config);
          const { code, data, message } = response.data;
          if (code === '200') {
            if (data && data.url) {
              this.resultImgurl = data.url;
              this.resultImgname = data.name;
            } else {
              throw new Error('图片上传失败，请重试！');
            }
          } else {
            throw new Error(message || '图片上传失败，请重试！');
          }
          const url = `api/file/download/${this.resultImgurl}`;
          this.currentItem.imageSrc = url;
        }
      } catch (err) {
        this.$emit('updateSignImg', '', this.signType);
      }
    },
    // 选择单位
    selectUnitUpdateData(data, index) {
      data.forEach(item => {
        this.form[index][item.name] = item.value;
      })
    },

  }
};
</script>

<style scoped>
:deep(.el-button-print .el-button) {
  display: inline-flex !important;
  visibility: visible !important;
  opacity: 1 !important;
  width: auto;
  min-width: 100px;
  height: auto;
  padding: 8px 15px;
  background: #fff !important;
  color: #000 !important;
  border: none;
}

:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 5mm;
  overflow-y: hidden;
  line-height: 1.3;
}

:deep(.el-textarea-hidden .el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 5mm;
  overflow-y: hidden !important;
  resize: none !important;
  height: auto !important;
}

.input-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}

.inputStyleNoLine {
  border: none;
  outline: none;
  padding: 0px;
}

.typeSpan {
  cursor: pointer;
  font-size: 5mm;
}
</style>
